package apiutil

type param map[string]interface{}
type hash map[string]interface{}

func (p param) require(key string) {
	if p[key] == nil {
		panic(fmt.Errorf("param %s is require, but get nil value", key))
	}
}

func (p param) requireString(key string) string {
	p.require(key)
	obj := p[key]
	value, ok := obj.(string)
	if ok {
		return value
	}
	panic(fmt.Errorf("can not parse %#v to string", obj))
}

func (p param) requireInt(key string) int {
	p.require(key)
	obj := p[key]
	value, ok := obj.(float64)
	if ok {
		return int(value)
	}
	panic(fmt.Errorf("can not parse %#v to int", obj))
}

func (p param) requireFloat(key string) float64 {
	p.require(key)
	obj := p[key]
	value, ok := obj.(float64)
	if ok {
		return value
	}
	panic(fmt.Errorf("can not parse %#v to float64", obj))
}

func (p param) requireHash(key string) hash {
	p.require(key)
	obj := p[key]
	value, ok := obj.(hash)
	if ok {
		return value
	}
	panic(fmt.Errorf("can not parse %#v to hash", obj))
}

func (p param) optionalString(key string, defaultValue string) string {
	obj, exist := p[key]
	if obj == nil || !exist {
		return defaultValue
	}
	value, ok := obj.(string)
	if ok {
		return value
	}
	panic(fmt.Errorf("can not parse %#v to string", obj))
}

func (p param) optionalInt(key string, defaultValue int) int {
	obj, exist := p[key]
	if obj == nil || !exist {
		return defaultValue
	}
	value, ok := obj.(float64)
	if ok {
		return int(value)
	}
	panic(fmt.Errorf("can not parse %#v to int", obj))
}

func (p param) optionalFloat(key string, defaultValue float64) float64 {
	obj, exist := p[key]
	if obj == nil || !exist {
		return defaultValue
	}
	value, ok := obj.(float64)
	if ok {
		return value
	}
	panic(fmt.Errorf("can not parse %#v to float64", obj))
}

func (p param) optionalHash(key string, defaultValue hash) hash {
	obj, exist := p[key]
	if obj == nil || !exist {
		return defaultValue
	}
	value, ok := obj.(hash)
	if ok {
		return value
	}
	panic(fmt.Errorf("can not parse %#v to hash", obj))
}
